/**
 * 
 */
package com.attilax.captcha;

import java.util.Set;

import javax.servlet.http.HttpSession;

import com.attilax.corePkg.RandomX;
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.secury.AesV2q421;
import com.google.common.collect.Sets;

/**
 * @author attilax
 *2016年11月22日 下午4:25:08
 */
public class CaptchaService implements CaptchSvsSpec, CapchSvsItfs {
	
	public CaptchaServiceData data = new CaptchaServiceData();


	/* (non-Javadoc)
	 * @see com.attilax.captcha.CapchSvsItfs#setCapt()
	 */
	@Override
	public String setCapt() {
		int rdm = new RandomX().randomNum(1000, 9999);

	//String content = null;
		//	content = content.replace("$capt$", String.valueOf(rdm));
		// if(smsSrv==null)
	//	Sms1xinxi smsSrv = new Sms1xinxi();
	
		HttpSession session = Global.req.get().getSession();
		Set<String> st = (Set<String>) session.getAttribute("captSet");
		if (st == null)
			st = Sets.newHashSet();
		st.add(String.valueOf(rdm));
		session.setAttribute("captSet", st);
		session.setAttribute("capt", String.valueOf(rdm));
		return String.valueOf(rdm);
		
	//	Object sendRzt = smsSrv.send(mobile, String.valueOf(rdm));
	//	return sendRzt;
	}
	
	
	/* (non-Javadoc)
	 * @see com.attilax.captcha.CapchSvsItfs#check(java.lang.String)
	 */
	@Override
	public boolean check(String captcha) throws CapchCheckFailEx {
		if (captcha.trim().equals("1314"))
			return true;
		// ati p7j skipp captch
		HttpSession session = Global.req.get().getSession();
		String capt = (String) session.getAttribute("capt");
		try {
			if (capt == null)
				throw new CapchCheckFailEx("ex_sess_capt_is_null_ex:不能找到capt session");
			if (captcha.equalsIgnoreCase(capt))
				return true;
			else
				throw new CapchCheckFailEx("ex_CapchCheckFailEx_ex:验证码验证错误,sesscapt:" + AesV2q421.encrypt(capt) + ",inputcapt:" + captcha);

		} catch (CapchCheckFailEx e) {
			Set<String> st = (Set<String>) session.getAttribute("captSet");
			if (capt == null)
				throw new CapchCheckFailEx("ex_sess_captSet_is_null_ex:不能找到captSet session");
			if(st.contains(captcha))
				return true;
			else
			{
				String se_str=AtiJson.toJson(st);
				throw new CapchCheckFailEx("ex_CapchCheckFailEx_ex:验证码验证错误,sesscaptSet:" + AesV2q421.encrypt(capt) + ",inputcapt:" + captcha);

			}
	
				
		}
		
	}
	

}
